import 'dart:io';

import 'package:chat_app_project/dao/im_dao.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:wukongimfluttersdk/common/options.dart' as wkOptions;
import 'package:wukongimfluttersdk/model/wk_image_content.dart';
import 'package:wukongimfluttersdk/model/wk_video_content.dart';
import 'package:wukongimfluttersdk/model/wk_voice_content.dart';
import 'package:wukongimfluttersdk/type/const.dart';
import 'package:wukongimfluttersdk/wkim.dart';

import '../components/conversation_content.dart';
import '../dao/file_dao.dart';
import '../models/const.dart';
import '../util/toast_util.dart';

class IMUtils {
  static Future<bool> initIM() async {
    if (!UserInfo.isLogin()) {
      return false;
    }
    bool result = await WKIM.shared
        .setup(wkOptions.Options.newDefault(UserInfo.uid, UserInfo.token));
    WKIM.shared.options.getAddr = (Function(String address) complete) async {
      String ip = await ImDao.getIP();
      complete(ip);
    };
    //注册自定义消息
    WKIM.shared.messageManager.registerMsgContent(100,
            (dynamic data) {
          return ConversationContent().decodeJson(data);
    });

    () async {
      WKIM.shared.connectionManager.connect();
    }.call();
    initListener();
    return result;
  }

  static initListener() {
    if (!UserInfo.isLogin()) {
      return false;
    }
    WKIM.shared.messageManager.addOnSyncChannelMsgListener((channelID,
        channelType, startMessageSeq, endMessageSeq, limit, pullMode, back) {
      debugPrint('回掉接口');
      // 同步某个频道的消息
      ImDao.syncChannelMsg(channelID, channelType, startMessageSeq,
          endMessageSeq, limit, pullMode, (p0) => back(p0));
    });

    WKIM.shared.conversationManager
        .addOnSyncConversationListener((lastSsgSeqs, msgCount, version, back) {
      ImDao.syncConversation(lastSsgSeqs, msgCount, version, back);
    });

    // 监听上传消息附件
    WKIM.shared.messageManager
        .addOnUploadAttachmentListener((wkMsg, back) async {
      if (wkMsg.contentType == WkMessageContentType.image) {
        //上传附件
        WKImageContent imageContent = wkMsg.messageContent! as WKImageContent;
        //所在路径
        var localPath = imageContent.localPath;
        // 选择的文件名
        var fileName = imageContent.localPath
            .substring(localPath.lastIndexOf("/") + 1, localPath.length);
        var file = File(localPath);
        // 文件转字节数组
        var bytes = file.readAsBytesSync();
        // var imageInfo = await FileUtil.getImageInfo(localPath);
        MultipartFile multipartFile = MultipartFile.fromBytes(
          bytes,
          filename: fileName,
        );
        //参数
        FormData data = FormData.fromMap({
          // file是上传的参数名，要与服务端接口定义对应
          "file": multipartFile,
          "biz": "im",
        });
        //上传文件
        FileDao.upload(data).then((response) {
          if (response.success) {
            var url = response.data;
            //网络路径
            imageContent.url = url;
            wkMsg.messageContent = imageContent;
            bool isSuccess = true; //default
            back(isSuccess, wkMsg);
          } else {
            // imageContent.url = 'xxxxxx';
            bool isSuccess = false; //default
            back(isSuccess, wkMsg);
            ToastUtil.toast("发送失败，请重试");
          }
        }, onError: (e) {
          bool isSuccess = false; //default
          back(isSuccess, wkMsg);
          ToastUtil.toast("发送失败，请重试");
        });
      }
      if (wkMsg.contentType == WkMessageContentType.voice) {
        // 上传语音
        WKVoiceContent voiceContent = wkMsg.messageContent! as WKVoiceContent;
        //所在路径
        var localPath = voiceContent.localPath;
        // 选择的文件名
        var fileName = voiceContent.localPath
            .substring(localPath.lastIndexOf("/") + 1, localPath.length);
        var file = File(localPath);
        // 文件转字节数组
        var bytes = file.readAsBytesSync();
        MultipartFile multipartFile = MultipartFile.fromBytes(
          bytes,
          filename: fileName,
        );
        //参数
        FormData data = FormData.fromMap({
          // file是上传的参数名，要与服务端接口定义对应
          "file": multipartFile,
          "biz": "im",
        });
        //上传文件
        FileDao.upload(data).then((response) {
          if (response.success) {
            var url = response.data;
            //网络路径
            voiceContent.url = url;
            wkMsg.messageContent = voiceContent;
            bool isSuccess = true; //default
            back(isSuccess, wkMsg);
          } else {
            // imageContent.url = 'xxxxxx';
            bool isSuccess = false; //default
            back(isSuccess, wkMsg);
            ToastUtil.toast("发送失败，请重试");
          }
        }, onError: (e) {
          bool isSuccess = false; //default
          back(isSuccess, wkMsg);
          ToastUtil.toast("发送失败，请重试");
        });
      } else if (wkMsg.contentType == WkMessageContentType.video) {
        WKVideoContent videoContent = wkMsg.messageContent! as WKVideoContent;
        //所在路径 封面
        var coverLocalPath = videoContent.coverLocalPath;
        // 选择的文件名
        var coverName = coverLocalPath.substring(
            coverLocalPath.lastIndexOf("/") + 1, coverLocalPath.length);
        var coverFile = File(coverLocalPath);
        MultipartFile multipartFile = MultipartFile.fromBytes(
          coverFile.readAsBytesSync(),
          filename: coverName,
        );
        //参数
        FormData data = FormData.fromMap({
          // file是上传的参数名，要与服务端接口定义对应
          "file": multipartFile,
          "biz": "im",
        });
        //上传封面
        var upload = await FileDao.upload(data);
        if (upload.success) {
          var url = upload.data;
          //网络路径
          videoContent.cover = url;
        } else {
          bool isSuccess = false; //default
          back(isSuccess, wkMsg);
          ToastUtil.toast("发送失败，请重试");
        }
        //所在路径  视频
        var vPath = videoContent.localPath;
        // 选择的文件名
        var vName = vPath.substring(vPath.lastIndexOf("/") + 1, vPath.length);
        var vFile = File(vPath);
        //参数
        FormData vData = FormData.fromMap({
          // file是上传的参数名，要与服务端接口定义对应
          "file": MultipartFile.fromBytes(
            vFile.readAsBytesSync(),
            filename: vName,
          ),
          "biz": "imv",
        });
        //上传视频
        var vUpload = await FileDao.upload(vData);
        if (vUpload.success) {
          var url = vUpload.data;
          //网络路径
          videoContent.url = url;
        } else {
          // imageContent.url = 'xxxxxx';
          bool isSuccess = false; //default
          back(isSuccess, wkMsg);
          ToastUtil.toast("发送失败，请重试");
        }
        //成功
        wkMsg.messageContent = videoContent;
        bool isSuccess = true; //default
        back(isSuccess, wkMsg);
      }
    });
  }

  static void disconnect() async {
    WKIM.shared.connectionManager.disconnect(true);
  }
}
